package com.ruoyi.business.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.domain.bo.CourseInfoBo;
import com.ruoyi.business.domain.vo.ChapterDetailVo;
import com.ruoyi.business.domain.vo.CourseInfoVo;
import com.ruoyi.business.domain.vo.UserVo;
import com.ruoyi.business.domain.vo.VideoDetailVo;
import com.ruoyi.business.mapper.*;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.domain.model.InternalObjectPage;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MailUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.domain.vo.InnerObjVo;
import com.ruoyi.system.service.ISysOssService;
import com.ruoyi.system.service.ISysTableObjService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 课程信息Service业务层处理
 *
 * @author 最爱喝兽奶
 * @date 2022-07-16
 */
@SuppressWarnings("ALL")
@Service
public class CourseInfoServiceImpl extends ServiceImpl<CourseInfoMapper, CourseInfo> implements ICourseInfoService
{
    @Autowired
    private CourseInfoMapper courseInfoMapper;

    @Autowired
    private ISysTableObjService sysTableObjService;

    @Autowired
    private ChapterInfoMapper chapterInfoMapper;

    @Autowired
    private CourseVideoMapper courseVideoMapper;

    @Autowired
    private THomeworkStuMapper homeworkStuMapper;

    @Autowired
    private HomeworkUserMapper homeworkUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CourseUserMapper courseUserMapper;

    @Autowired
    private ICourseUserService courseUserService;


    @Autowired
    private IChapterInfoService chapterInfoService;

    @Autowired
    private ICourseVideoService courseVideoService;

    @Autowired
    private ISysOssService ossService;

    @Autowired
    private MailUtils mailUtils;

    /**
     * 查询课程信息
     *
     * @param id 课程信息主键
     * @return 课程信息
     */
    @Override
    public CourseInfo selectTCourseInfoById(String id)
    {
        return courseInfoMapper.selectById(id);
    }

    /**
     * 查询课程信息列表
     *
     * @param tCourseInfo 课程信息
     * @return 课程信息
     */
    @Override
    public TableDataInfo<CourseInfoVo> selectTCourseInfoList(CourseInfoBo bo)
    {
        Page<CourseInfo> page = baseMapper.selectCourseListByPage(PageUtils.buildPage(bo), bo);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        List<CourseInfoVo> collect = page.getRecords().stream().map(item -> {
            CourseInfoVo vo = new CourseInfoVo();
            BeanUtils.copyProperties(item, vo);
            SysOss sysOss = ossService.queryById(item.getCourseImage());
            String status = "1";
            if (System.currentTimeMillis() - item.getEndTime().getTime() < 0) {
                status = "0";
            }
            if (!status.equals(item.getStatus())) {
                item.setStatus(status);
                baseMapper.updateById(item);
            }
            if ("0".equals(item.getStatus())) {
                // 课程状态正常
                vo.setStatus(true);
            }else {
                // 课程状态不正常
                vo.setStatus(false);
            }
            vo.setStartTime(sdf.format(item.getStartTime()));
            vo.setEndTime(sdf.format(item.getEndTime()));
            vo.setCourseImage(sysOss.getUrl());
            return vo;
        }).collect(Collectors.toList());
        Page<CourseInfoVo> res = new Page<>();
        res.setTotal(page.getTotal());
        res.setCurrent(page.getCurrent());
        res.setSize(page.getSize());
        res.setRecords(collect);
        return PageUtils.buildTableDataInfo(res);
    }


    /**
     * 查询课程信息列表
     *
     * @param id 课程类型
     * @return 课程信息
     */

    @Override
    public List<CourseInfoVo> selectCourseBySeries(String id) {
        return courseInfoMapper.selectCourseBySeries(id);
    }



    /**
     * 新增课程信息
     *
     * @param tCourseInfo 课程信息
     * @return 结果
     */
    @Override
    public String insertTCourseInfo(CourseInfoBo bo)
    {
        CourseInfo tCourseInfo = null;
        if (null == bo.getId()) {
            tCourseInfo = new CourseInfo();
            BeanUtils.copyBeanProp(tCourseInfo, bo, false);
            if (null == bo.getUploadTeacher()) {
                tCourseInfo.setUploadTeacher(String.valueOf(SecurityUtils.getUserId()));
            }
            // 如果没有传入id就说明是第一次，直接插入，
            courseInfoMapper.insert(tCourseInfo);
        }else {
            tCourseInfo = courseInfoMapper.selectById(bo.getId());
            if (null == tCourseInfo) {
                throw new RuntimeException("请传入正确的id");
            }
            BeanUtils.copyBeanProp(tCourseInfo, bo, true);
            // 如果传入了id，就
            courseInfoMapper.updateById(tCourseInfo);
        }
        return tCourseInfo.getId();
    }

    /**
     * 修改课程信息
     *
     * @param tCourseInfo 课程信息
     * @return 结果
     */
    @Override
    public String updateTCourseInfo(CourseInfoBo bo)
    {
        CourseInfo tCourseInfo = courseInfoMapper.selectById(bo.getId());
        if (null == tCourseInfo) {
            throw new RuntimeException("请传入正确的id");
        }
        BeanUtils.copyBeanProp(tCourseInfo, bo, false);
        // 如果传入了id，就
        courseInfoMapper.updateById(tCourseInfo);
        return tCourseInfo.getId();
    }


    /**
     * 修改课程信息
     *
     * @param tCourseInfo 课程信息
     * @return 结果
     */
    @Override
    public String updateTCourseStatus(CourseInfoBo bo)
    {
        CourseInfo tCourseInfo = courseInfoMapper.selectById(bo.getId());
        tCourseInfo.setStatus("1");
        if (null == tCourseInfo) {
            throw new RuntimeException("请传入正确的id");
        }

        courseInfoMapper.updateById(tCourseInfo);
        return tCourseInfo.getId();
    }



    /**
     * 修改课程状态
     *
     * @param tCourseInfo 课程信息
     * @return 结果
     */
    @Override
    public String offTCourseStatus(CourseInfoBo bo)
    {
        CourseInfo tCourseInfo = courseInfoMapper.selectById(bo.getId());
        tCourseInfo.setStatus("0");
        if (null == tCourseInfo) {
            throw new RuntimeException("请传入正确的id");
        }

        courseInfoMapper.updateById(tCourseInfo);
        return tCourseInfo.getId();
    }




    /**
     * 批量删除课程信息
     *
     * @param ids 需要删除的课程信息主键
     * @return 结果
     */
    @Override
    public int deleteTCourseInfoByIds(Long[] ids)
    {
        List<Long> idList = new ArrayList<>();
        for (Long id : ids) {
            if (null != id) {
                idList.add(id);
            }
        }
        return courseInfoMapper.deleteBatchIds(idList);
    }

    /**
     * 删除课程信息信息
     *
     * @param id 课程信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTCourseInfoById(Long id)
    {
        CourseInfo courseInfo = getById(id);
        List<ChapterInfo> chapterInfos = chapterInfoService.queryChaptersByCourseId(id);
        for (ChapterInfo chapterInfo : chapterInfos) {
            courseVideoService.deleteCourseVideoByChapterId(chapterInfo.getId());
            chapterInfoService.removeById(courseInfo.getId());
        }
        return courseInfoMapper.deleteById(id);
    }

    @Override
    public List<InnerObjVo> queryRefCourseInfo(String teacherId) {
        List<InnerObjVo> list = courseInfoMapper.queryRefCourseInfoByTeacherId(teacherId);
        return list;
    }

    @Override
    public List<CourseInfoVo> selectAll(CourseInfoBo bo) {
        String userId = SecurityUtils.getUserId();
        if (!SecurityUtils.isAdmin(userId) && StringUtils.isNotBlank(bo.getUploadTeacher())) {
            bo.setUploadTeacher(userId);
        }else {
            bo.setUploadTeacher(null);
        }
        List<CourseInfoVo> collect = courseInfoMapper.selectListVo(bo).stream().map(item -> {
            String num = baseMapper.selectCourseUsersNum(item.getId());
            item.setNum(Long.parseLong(num));
            return item;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<CourseInfoVo> selectOneCourse(String id) {

        List<CourseInfoVo> courseInfoVos = courseInfoMapper.selectOneCourse(id);
        List<CourseInfoVo> collect = courseInfoVos.stream().map(item -> {
            User user = userMapper.selectById(item.getUploadTeacher());
            item.setUploadTeacher(user.getNickName());
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Date endTime = sdf.parse(item.getEndTime());
                if (new Date().getTime() > endTime.getTime()) {
                    item.setStatus(false);
                }else {
                    item.setStatus(true);
                }
            } catch (Exception e) {
                log.error("请重新上传正确的课程截止时间");
                e.printStackTrace();
            }
            return item;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<ChapterDetailVo> selectCourseChapter(String id) {
        List<ChapterDetailVo> list = chapterInfoMapper.queryCourseChapter(id);

        list.forEach(e ->{
            if (StringUtils.isNotEmpty(e.getId())) {
                List<VideoDetailVo> videoDetailVoList = courseVideoMapper.selectByChapterId(e.getId());
                e.setVideoList(videoDetailVoList);
            }
        });

        return  list;
    }

    @Override
    public String SelectVideoUrl(String id) {
        String url = courseVideoMapper.selectUrlById(id);

        return url;
    }
    @Override
    public InternalObjectPage selectRefTableByName(String refColumn, Integer pageSize, Integer currentPage, String filterContent, String filterId) {
        InternalObjectPage pageDomain = new InternalObjectPage();
        //主键Map
        Map<String, String[]> pkMap = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        //标题头
        Map<String, Map<String, String>> titleMap = new LinkedHashMap();
        String sql = null;
        Page pageList = new Page();
        Page page = new Page();
        //是否开启分页，不开启默认查询前10000条记录（前端已限制默认分页数量，此处为保障内部对象的正常使用）
        if (currentPage == null || pageSize == null) {
            page = new Page(1, 10000);
        } else {
            page = new Page(currentPage, pageSize);
        }
        String[] refColumns = {"course"};
        if (StringUtils.equalsAnyIgnoreCase(refColumn, refColumns)) {

            Map<String, String> courseMap = new LinkedHashMap();
            courseMap.put("showColumn", "课程");
            titleMap.put("course", courseMap);
            pkMap.put("course", new String[]{"id", "course_name"});
            map.put("course", "SELECT id as \"refColumn\",course_name as \"showColumn\"   FROM T_COURSE_INFO");

            sql = map.get(refColumn);
            //筛选
            if (StringUtils.isNotEmpty(filterContent)) {
                if (StringUtils.isNotEmpty(pkMap.get(refColumn)[1])) {
                    sql = sql + " where  " + pkMap.get(refColumn)[1] + " like " + "'%" + filterContent + "%'";
                }
            }
            //回显与判断
            if (StringUtils.isNotEmpty(filterId)) {
                List<String> list = Arrays.asList(filterId.split(","));
                String ids = list.stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(","));
                if (StringUtils.isNotEmpty(pkMap.get(refColumn))) {
                    sql = sql + " where " + pkMap.get(refColumn)[0] + " in " + "(" + ids + ")";
                }
            }
        }
        try {
            pageList = sysTableObjService.executeSelectSqlSelectRefTableByName(page, sql);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException().setMessage("内部对象字段配置信息错误");
        }
        List<Map<String, String>> records = (List<Map<String, String>>) pageList.getRecords().stream().map(item -> {
            if (item instanceof Map) {
                Map m = (Map) item;
                if (m.containsKey("refColumn")) {
                    Object value = m.get("refColumn");
                    if (value instanceof BigInteger) {
                        m.put("refColumn", String.valueOf(value));
                    }
                }
            }
            return item;
        }).collect(Collectors.toList());
        pageDomain.setTotal(page.getTotal());
        pageDomain.setTitle(titleMap.get(refColumn));
        pageDomain.setDataList(records);
        return pageDomain;
    }

    @Override
    public String SelectVideoName(String id) {
        String name= courseVideoMapper.selectNameById(id);

        return  name;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean subScribeCourse(String id) {
        CourseUser courseUser = new CourseUser();
        courseUser.setCourseId(id);
        courseUser.setUserId(String.valueOf(SecurityUtils.getUserId()));
        courseUserMapper.insert(courseUser);
        return true;
    }

    @Override
    public Boolean queryIfSubScribe(String id) {
        QueryWrapper<CourseUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", String.valueOf(SecurityUtils.getUserId()));
        wrapper.eq("course_id", id);
        List<CourseUser> courseUsers = courseUserMapper.selectList(wrapper);
        if (null != courseUsers && courseUsers.size() == 1) {
            return true;
        }
        return false;
    }

    @Override
    public void assignClassForCourse(CourseInfoBo bo) {
        List<THomeworkStu> list = new ArrayList<>();
        if (StringUtils.isNotBlank(bo.getAssignClass())) {
            CourseInfo courseInfo = courseInfoMapper.selectById(bo.getId());
            String username = SecurityUtils.getUsername();
            // 如果指派的班级不为空
            // 先查询出班级里的学生,魔法值出现了
            List<String> emails = new ArrayList<>();
            List<UserVo> users = userMapper.selectUserByClass(bo.getAssignClass().split(","));
            if (null != users) {
                List<CourseUser> courseUsers = new ArrayList<>();
                for (UserVo user : users) {
                    // 先查询当前学生是否已经预定了这门课
                    QueryWrapper<CourseUser> wrapper = new QueryWrapper<>();
                    wrapper.eq("user_id", user.getUserId());
                    wrapper.eq("course_id", bo.getId());
                    CourseUser one = courseUserMapper.selectOne(wrapper);
                    if (null == one) {
                        CourseUser courseUser = new CourseUser();
                        courseUser.setUserId(user.getUserId());
                        courseUser.setCourseId(bo.getId());
                        courseUserMapper.insert(courseUser);
                        emails.add(user.getEmail());
                    }
                }
                mailUtils.sendMessage(emails,
                        username + "老师刚刚发布了课程《" + courseInfo.getCourseName() + "》请注意跟进!", "发布课程");
            }
        }
    }
}
